package cz.hanis.android.geography.adapters;

import java.util.List;

import cz.hanis.android.geography.GeographyApplication;
import cz.hanis.android.geography.R;
import cz.hanis.android.geography.WrongResourceException;
import cz.hanis.android.geography.R.id;
import cz.hanis.android.geography.R.layout;
import cz.hanis.android.geography.models.Country;




import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CountryArrayAdapter extends ArrayAdapter<Country> {

	private static final String TAG = "CountryArrayAdapter";
	
	private List<Country> mCountries;
	private Activity mContext;
	
	public CountryArrayAdapter(Activity context, List<Country> countries) {
		super(context, R.layout.country_row, R.id.tv_country_list_label, countries);
		mCountries = countries;
		mContext = context;
	}

	
	static class ViewHolder {
		public TextView text;
		public ImageView image;
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View rowView = convertView;
		if (rowView == null) {
			LayoutInflater inflater = mContext.getLayoutInflater();
			rowView = inflater.inflate(R.layout.country_row, null);
			ViewHolder viewHolder = new ViewHolder();
			viewHolder.text = (TextView) rowView.findViewById(R.id.tv_country_list_label);
			viewHolder.image = (ImageView) rowView.findViewById(R.id.iv_country_list_icon);
			rowView.setTag(viewHolder);
		}

		ViewHolder holder = (ViewHolder) rowView.getTag();
		Country country = mCountries.get(position);
		holder.text.setText(country.getName());		
		try {
			holder.image.setImageDrawable(GeographyApplication.getInstance().getFlagDrawable(country.getId()));
		} catch (WrongResourceException e) {
			Log.d(CountryArrayAdapter.TAG, e.getMessage());
	    }
		return rowView;
	}	
	
	public List<Country> getCountries() {
		return mCountries;
	}
	
	public void setCountries(List<Country> countries) {
		mCountries.clear();
		mCountries.addAll(countries);
		notifyDataSetChanged();
	}

	
}
